<template>
  <div class="app-container">
    <div class="table-box">
      <!-- 按钮功能区 开始 -->
      <el-row :gutter="10" class="btn-box">
        <el-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="24"
          :xl="24"
          class="btnfunction-section-col"
        >
          <el-button type="primary" icon="el-icon-plus" :disabled="!checkPermission(['admin.menu.store'])" @click="handleCreate()">
            {{ $t('common.create') }}
          </el-button>
          <el-button type="primary" icon="awesome-icon fas fa-sort" :disabled="!checkPermission(['admin.menu.updateSort'])" @click="handleUpdateSort()">
            {{ $t('common.updateSort') }}
          </el-button>
          <el-button-group>
            <el-button
              icon="el-icon-sort"
              :title="$t('common.updown')"
              @click="handleUpDown()"
            >
              {{ $t('common.updown') }}
            </el-button>
          </el-button-group>
          <el-button icon="el-icon-refresh" @click="handleRefresh">{{
            $t('common.refresh')
          }}</el-button>
        </el-col>
      </el-row>
      <!-- 按钮功能区 结束 -->

      <!-- Note that row-key is necessary to get a correct row order.   table当前行高亮属性highlight-current-row-->
      <el-table
        ref="treeTable"
        :key="1"
        v-loading="listLoading"
        :data="list"
        row-key="id"
        border
        fit
        highlight-current-row
        :default-expand-all="isExpand"
        style="width: 100%"
        :indent="12"
        max-height="540px"
        @selection-change="handleSelectionChange"
        @select-all="selectAll"
      >
        <el-table-column type="selection" align="center" fixed="left" />

        <el-table-column
          align="left"
          :label="$t('menu.name')"
          class-name="menuIcon"
          min-width="220px"
        >
          <template slot-scope="{ row }">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('menu.type')"
          min-width="80px"
        >
          <template slot-scope="{ row }">
            <el-tag :type="row.type!=3 ? '' : 'info' ">
              <span>{{ row.type | paraseDictionaryItemName('menuTypeVar') }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('menu.route_icon')"
          min-width="80px"
        >
          <template slot-scope="{ row }">
            <span v-if="row.route_icon"><jsp-icon :icon="row.route_icon" /></span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('menu.route_name')"
          min-width="150px"
        >
          <template slot-scope="{ row }">
            <span v-text="row.route_name?row.route_name:'-'" />
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('menu.route_path')"
          min-width="150px"
        >
          <template slot-scope="{ row }">
            <span v-text="row.route_path?row.route_path:'-'" />
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('menu.route_component')"
          min-width="150px"
        >
          <template slot-scope="{ row }">
            <span v-text="row.route_component?row.route_component:'-'" />
          </template>
        </el-table-column>
        <el-table-column align="center" width="80">
          <template slot="header">
            <span> {{ $t('menu.permission') }} </span>
            <el-tooltip class="item" effect="dark" placement="right">
              <div
                slot="content"
                v-html="$t('menu.table_header_permission_tips')"
              />
              <i class="awesome-icon fas fa-question-circle" />
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <span v-if="row.permission_items.length>0" class="link-type" :title="$t('common.click_view')" @click="handlePermissionView(row)">
              {{ $t('common.view') }}
            </span>
            <span v-else class="link-type" v-text="'-'" />
          </template>
        </el-table-column>

        <el-table-column width="180" :label="$t('common.sort')" prop="sort" align="center">
          <template slot-scope="{ row }">
            <el-input-number v-model="row.sort" controls-position="right" :min="1" />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('menu.status')"
          class-name="status-col"
          width="80"
        >
          <template slot-scope="{ row }">
            <el-switch
              v-model.number="row.status"
              :active-value="1"
              :inactive-value="0"
              :disabled="!checkPermission(['admin.menu.updateStatus'])"
              @change="handleModifyStatus($event,row)"
            />

          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.created_at')"
          width="180"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.created_at }}</span>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.operation')"
          align="center"
          class-name="small-padding fixed-width"
          width="200px"
          fixed="right"
        >
          <template slot-scope="{ row, $index }">
            <el-link
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.menu.update'])&&!checkPermission(['admin.menu.show'])"
              icon="el-icon-edit"
              :title="$t('common.edit')"
              @click="handleEdit(row)"
            >{{ $t('common.edit') }}
            </el-link>&nbsp;
            <el-link
              v-if="row.type==1&&row.relation_cate!=1"
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.menu.store'])"
              icon="el-icon-plus"
              :title="$t('common.create')"
              @click="handleCreate(row)"
            >{{ $t('common.create') }}
            </el-link>&nbsp;
            <el-link
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.menu.destroy'])"
              icon="el-icon-delete"
              :title="$t('common.delete')"
              @click="handleDelete(row, $index)"
            >{{ $t('common.delete') }}
            </el-link>&nbsp;
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="viewItem.name+$t('menu.permission')" :visible.sync="viewDialog" class="table-box" custom-class="jsp-dialog-modal-box">
      <el-table :key="2" :data="viewItem.permission_items" max-height="540px">
        <el-table-column property="name" :label="$t('common.name')" />
        <el-table-column
          :label="$t('common.permission')"
          property="priv"
        >
          <template slot-scope="{ row }">
            <span class="link-type" :title="$t('common.click_copy')" @click="clipboard(`v-permission=&quot;['${row.priv}']&quot;`, $event)">{{ row.priv }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      :title="editType?$t('common.edit'):$t('common.create')"
      :visible.sync="menuEditDialogFormVisible"
      top="5vh"
      :close-on-click-modal="false"
      destroy-on-close
      custom-class="jsp-dialog-modal-box"
    >
      <menu-edit-dialog v-if="menuEditDialogFormVisible" ref="menuEditDialog" :edit-detail="editDetail" @error="handleEditError" @success="handleEditSuccess" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuEditDialogFormVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button
          type="primary"
          :loading="editDetailSubmitLoading"
          :disabled="editType&&!checkPermission(['admin.menu.update']) || !editType&&!checkPermission(['admin.menu.store'])"
          @click="handleMenuEditSubmit"
        >{{ $t('common.submit') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { index, updateStatus, destory, updateSort } from '@/api/menu'
import { treeToFlat } from '@/utils/tree'
import clipboard from '@/utils/clipboard'
import JspIcon from '@/components/JspIcon'
import MenuEditDialog from './editDialog'
import checkPermission from '@/utils/permission'

export default {
  name: 'MenuIndex',
  components: {
    JspIcon,
    MenuEditDialog
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      listQuery: {
        sort: '+sort'
      },
      total: 0,
      listLoading: true,
      multipleSelection: [],
      isSelected: false,
      isExpand: false,
      flatList: [],
      viewItem: {},
      viewDialog: false,
      menuEditDialogFormVisible: false,
      editType: 0,
      editDetail: {},
      editDetailSubmitLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    clipboard,
    async getList() {
      this.listLoading = true
      await index(this.listQuery).then((response) => {
        const { items, total } = response.data
        this.total = total
        this.list = items
        this.flatList = treeToFlat(items)
        this.listLoading = false
      }).catch(() => {
        this.closeBack()
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    selectAll(selection) {
      this.isSelected = !this.isSelected
      this.flatList.forEach((row, index) => {
        this.$refs.treeTable.toggleRowSelection(row, this.isSelected)
      })
    },
    handleDelete(row, index) {
      this.$confirm(this.$t('common.delete_confirm_tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      })
        .then(() => {
          destory(row.id).then((response) => {
            this.$message.success(response.message)
            this.getList()
          }).catch(() => {
          })
        })
        .catch(() => {
          this.$message.info(this.$t('common.canceled'))
        })
    },
    handleUpdateSort() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('common.please_choose_sort_tips'))
        return
      }
      const params = this.multipleSelection.map((row, index) => {
        return { id: row.id, sort: row.sort }
      })
      updateSort({ sort: params }).then((response) => {
        this.$message.success(response.message)
        this.getList()
      }).catch(() => {
      })
    },
    handleModifyStatus($event, row) {
      updateStatus(row.id, { status: $event }).then((response) => {
        this.$message.success(response.message)
        row.status = $event
      }).catch(() => {
      })
    },
    downUpData(data, isExpand) {
      data.forEach((i) => {
        if (i.children) {
          this.$refs.treeTable.toggleRowExpansion(i, isExpand)
          this.downUpData(i.children, isExpand)
        }
      })
    },
    handleUpDown() {
      this.isExpand = !this.isExpand
      this.downUpData(this.list, this.isExpand)
    },
    handleRefresh() {
      this.getList()
    },
    handlePermissionView(row) {
      this.viewDialog = true
      this.viewItem = row
    },
    handleCreate(parent) {
      this.editDetail.id = 0
      this.editDetail.parent_id = parent !== undefined ? parent.id : 0
      this.menuEditDialogFormVisible = true
      this.editType = 0
    },
    handleEdit(row) {
      this.editDetail = { id: row.id, parent_id: row.parent_id }
      this.menuEditDialogFormVisible = true
      this.editType = 1
    },
    // 提交编辑表单
    // eslint-disable-next-line handle-callback-err
    handleMenuEditSubmit() {
      this.editDetailSubmitLoading = true
      this.$refs.menuEditDialog.onSubmit()
    },
    // eslint-disable-next-line handle-callback-err
    handleEditError(error) {
      this.editDetailSubmitLoading = false
      // error !== null && this.$message.error(error)
    },
    handleEditSuccess(response) {
      this.editDetailSubmitLoading = false
      this.$message.success(response.message)
      this.menuEditDialogFormVisible = false
      this.handleRefresh()
    }
  }
}
</script>

<style scoped>
</style>
